import React, { Component } from 'react';
import {
    StyleSheet,
    Text,
    View,
    TouchableOpacity,
    Image,
    FlatList,
    StatusBar,
    TextInput,
    ScrollView,
    Picker,
    DeviceEventEmitter, WebView
} from 'react-native';
import { base } from "../../../../assets/style";
import LinearGradient from "react-native-linear-gradient";
import ReactNativePickerSelect from 'react-native-picker-select'
import {API} from "../../../../api";
import {getUserInfo} from "../../../../utils/login";
import Loading from "../../../../components/loading";
import Toast from "react-native-easy-toast";
import {i18n} from "../../../../utils/locales/i18n";
import {EMAIL_REG_EXP, geetestURL_8080, PHONE_REGEXP_HK, PHONE_REGEXP_ZH} from "../../../../config";

type Props = {};
export default class VerifyPhone extends Component<Props> {
    static navigationOptions = ({ navigation }) => {
        return {
            title: i18n.t('i53'),
            headerStyle: {
            },
            headerTintColor: '#0f0f0f',
            headerBackTitle: null
        }
    };
    constructor() {
        super();
        this.state = {
            phoneNumber: '',
            messageCode: '',
            district: '+86',
            geetestVisible: false,
            isSend: false,
            second: 60,
            showLoading: false,
            info: ''
        }
    }
    // 获取验证码
    getVerifyCode = async () => {
        if (this.state.phoneNumber === '') {
            this.refs.toast.show(i18n.t('i54'))
            return
        }
        if ((this.state.district === '+86' && !PHONE_REGEXP_ZH.test(this.state.phoneNumber)) || (this.state.district === '+852' && !PHONE_REGEXP_HK.test(this.state.phoneNumber))) {
            this.refs.toast.show(i18n.t('i241'))
            return
        }
        // 检测手机是否已经注册过，有则不让注册
        const vRes = await API.checkPhone({phone: this.state.phoneNumber})
        console.log('vRes', vRes);
        if (vRes.code === 10004) {
            this.refs.toast.show(vRes.msg || i18n.t('i239'))
            return
        }
        this.setState({
            geetestVisible: true
        })
    }
    // webview加载失败处理
    onGeetestError = () => {
        this.setState({
            geetestVisible: false
        })
        alert('Geetest faild!')
    }
    // 处理极验返回的消息
    handleGeetestMessage = (e) => {
        e.persist();
        if (e.nativeEvent.data === 'send') {
            // 成功发送，隐藏webview
            setTimeout(() => {
                this.setState({
                    geetestVisible: false,
                    isSend: true
                })
                // 重新发送倒计时
                const timer = setInterval(() => {
                    this.setState({
                        second: this.state.second - 1
                    })
                    if (this.state.second <= 0) {
                        clearInterval(timer)
                        this.setState({
                            second: 60,
                            isSend: false
                        })
                    }
                }, 1000)
            }, 0)
        }
    }
    // 向极验webview 发送数据
    sendMessageToGeetest = () => {
        // type: 1注册 2绑定 3设置 4重置登陆密码 5重置资金密码 6提币验证码
        let options = {
            to: this.state.district + this.state.phoneNumber,
            type: 2
        }
        this.refs.webview.postMessage(JSON.stringify(options))
    }
    // 提交
    bindPhone = async () => {
        if (!this.state.phoneNumber || !this.state.messageCode || !this.state.district) {
            this.refs.toast.show(i18n.t('plz_cpl'))
            return
        }
        this.setState({
            showLoading: true,
            info: i18n.t('loading')
        })
        // console.log('reqparam', {
        //     'areaCode': this.state.district.slice(1),
        //     'phone': this.state.phoneNumber,
        //     'captcha': this.state.messageCode
        // })
        const res = await API._fetch('bindPhone', {
            'areaCode': this.state.district.slice(1),
            'phone': this.state.phoneNumber,
            'captcha': this.state.messageCode
        })
        // console.log(res);
        if (res && res.code && res.code === 10000) {
            this.setState({
                showLoading: false,
                info: ''
            })
            this.refs.toast.show(i18n.t('o_success'))
            setTimeout(async () => {
                // 重新请求user-info
                await getUserInfo()
                // 返回上一层
                setTimeout(() => {
                    DeviceEventEmitter.emit('refresh_user_info');
                    this.props.navigation.goBack()
                }, 0)
            })
        } else {
            this.setState({
                showLoading: false,
                info: ''
            })
            this.refs.toast.show( res.msg || i18n.t('o_defeat'))
        }
    }
    render() {
        return (
            <View style={[base.flex_1]}>
                { this.state.showLoading ? (
                    <Loading
                        info={this.state.info}
                    />
                ) : null}
                <Toast ref={'toast'} position={'bottom'} positionValue={200 }/>
                {/*极验验证 */}
                { this.state.geetestVisible ? (
                    <View style={{ position: 'absolute', top: 0, left: 0, width: '100%', height: '100%', zIndex: 999 }}>
                        <WebView
                            ref={'webview'}
                            onMessage={ msg => this.handleGeetestMessage(msg)}
                            onLoad={this.sendMessageToGeetest}
                            bounces={false}
                            javaScriptEnabled={true}
                            onError={this.onGeetestError}
                            style={{ flex: 1 }}
                            // source={require('../../../../pages/geetest_8080.html')}
                            source={{uri: geetestURL_8080}}
                        />
                    </View>
                ) : null}
                <View style={[base.flex_1, base.bg_gray, base.content_container]}>
                    <View style={{paddingHorizontal: 15, paddingBottom: 20, backgroundColor: '#fff', alignItems: 'center', marginTop: 10, borderRadius: 5 }}>
                        <View>
                            <Image style={{width: 200, height: 200}} resizeMode={'contain'} source={require('@images/mine/verify_phone.png')}/>
                        </View>
                        {/*<View style={[base.flex_row_between, { marginVertical: 5, height: 45, width: '100%', borderRadius: 5, borderWidth: 1, borderColor: '#d2d2d2', paddingHorizontal: 15 }]}>*/}
                        {/*<Text style={[base.color_gray]}>(+86) China</Text>*/}
                        {/*<TouchableOpacity style={[base.flex_1, base.flex_row_end, { height: '100%' }]}>*/}
                        {/*<Image resizeMode={'contain'} style={{width: 10, height: 10}} source={require('@images/mine/icon_triangle.png')}/>*/}
                        {/*</TouchableOpacity>*/}
                        {/*</View>*/}
                        <View style={{position: 'relative', width: '100%'}}>
                            <ReactNativePickerSelect
                                style={{...pickerSelectStyles}}
                                items={[
                                    { label: '(+86) China', value: '+86' },
                                    { label: '(+852) Hong Kong', value: '+852' }
                                ]}
                                hideIcon={true}
                                value={this.state.district}
                                onValueChange={(district) => {this.setState({district})}}
                            />
                            <Image resizeMode={'contain'} style={{width: 10, height: 10, position: 'absolute', top: '40%', right: 20}} source={require('@images/mine/icon_triangle.png')}/>
                        </View>
                        <View style={[base.flex_row_between, { marginVertical: 5, height: 45, width: '100%', borderRadius: 5, borderWidth: 0.5, borderColor: '#d2d2d2', paddingHorizontal: 15 }]}>
                            <TextInput
                                style={[base.color_gray, {width: '100%'}]}
                                value={this.state.phoneNumber}
                                onChangeText={(text) => this.setState({phoneNumber: text})}
                                placeholder={i18n.t('i55')}
                            />
                        </View>
                        <View style={{ height: 45, width: '100%', borderColor: '#d2d2d2', borderWidth: 0.5, borderRadius: 5, marginVertical: 10, flexDirection: 'row' }}>
                            <TextInput
                                style={{color: '#808080', width: '100%', height: '100%', flex: 1, paddingLeft: 15, borderRightColor: '#d2d2d2', borderRightWidth: 1}}
                                onChangeText={(text) => this.setState({messageCode: text})}
                                placeholder={i18n.t('c_message')}
                                value={this.state.messageCode}
                            />
                            { !this.state.isSend ? (
                                <TouchableOpacity style={{width: 100, height: '100%'}} onPress={this.getVerifyCode}>
                                    <View style={[base.flex_1, base.flex_row_center]}>
                                        <Text style={[base.color_orange, {fontSize: 16}]}>{i18n.t('cag')}</Text>
                                    </View>
                                </TouchableOpacity>
                            ) : (
                                <TouchableOpacity style={{width: 100, height: '100%'}}>
                                    <View style={[base.flex_1, base.flex_row_center]}>
                                        <Text style={[base.color_gray, {fontSize: 12}]}> {this.state.second} s</Text>
                                    </View>
                                </TouchableOpacity>
                            ) }
                        </View>
                    </View>
                    <View style={[base.flex_1, base.flex_col_center, { paddingBottom: 30 }]}>
                        <TouchableOpacity style={{width: '100%'}} onPress={this.bindPhone}>
                            <LinearGradient
                                start={{x: 0, y: 0}}
                                end={{x: 1, y: 1}}
                                colors={['#feac1c', '#ff7506']}
                                style={{ width: '100%', height: 46, borderRadius: 23, justifyContent: 'center', alignItems: 'center' }}
                            >
                                <Text style={{color: '#fff', fontSize: 16}}>{i18n.t('save')}</Text>
                            </LinearGradient>
                        </TouchableOpacity>
                    </View>
                </View>
            </View>
        )
    }
}

const styles = StyleSheet.create({
});
const pickerSelectStyles = StyleSheet.create({
    inputIOS: {
        display: 'flex',
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        height: 45,
        paddingHorizontal: 15,
        borderWidth: 0.5,
        borderColor: '#d2d2d2',
        borderRadius: 5,
        backgroundColor: 'white',
        color: '#808080',
        marginVertical: 5
    },
    inputAndroid: {
        display: 'flex',
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        height: 45,
        paddingHorizontal: 15,
        borderWidth: 0.5,
        borderColor: '#d2d2d2',
        borderRadius: 5,
        backgroundColor: 'white',
        color: '#808080',
        marginVertical: 5
    },
});
